home *** CD-ROM | disk | FTP | other *** search
/ AGA Toolkit '97 / The AGA Toolkit '97.iso / programming / c / make-3.75 / job.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-09-07  |  40.5 KB  |  1,615 lines

  1. /* Job execution and handling for GNU Make.
  2. Copyright (C) 1988, 89, 90, 91, 92, 93, 94, 1995 Free Software Foundation, Inc.
  3. This file is part of GNU Make.
  4.  
  5. GNU Make is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9.  
  10. GNU Make is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. GNU General Public License for more details.
  14.  
  15. You should have received a copy of the GNU General Public License
  16. along with GNU Make; see the file COPYING.  If not, write to
  17. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  18.  
  19. #include "make.h"
  20. #include "commands.h"
  21. #include "job.h"
  22. #include "file.h"
  23. #include "variable.h"
  24. #include <assert.h>
  25.  
  26. /* Default shell to use.  */
  27. #ifndef _AMIGA
  28. char default_shell[] = "/bin/sh";
  29. #else
  30. char default_shell[] = "";
  31. extern int MyExecute (char **);
  32. #endif
  33.  
  34. #ifdef __MSDOS__
  35. #include <process.h>
  36. static int dos_pid = 123;
  37. static int dos_status;
  38. static char *dos_bname;
  39. static char *dos_bename;
  40. static int dos_batch_file;
  41. #endif /* MSDOS.  */
  42. #ifdef _AMIGA
  43. #include <proto/dos.h>
  44. static int amiga_pid = 123;
  45. static int amiga_status;
  46. static char amiga_bname[32];
  47. static int amiga_batch_file;
  48. #endif /* MSDOS.  */
  49.  
  50.  
  51. /* If NGROUPS_MAX == 0 then try other methods for finding a real value.  */
  52. #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0
  53. #undef NGROUPS_MAX
  54. #endif /* NGROUPS_MAX == 0 */
  55.  
  56. #ifndef NGROUPS_MAX
  57. #ifdef    POSIX
  58. #define GET_NGROUPS_MAX sysconf (_SC_NGROUPS_MAX)
  59. #else    /* Not POSIX.  */
  60. #define NGROUPS_MAX    NGROUPS
  61. #endif    /* POSIX.  */
  62. #endif
  63.  
  64. #ifdef    HAVE_SYS_WAIT_H
  65. #include <sys/wait.h>
  66. #endif
  67.  
  68. #ifdef    HAVE_WAITPID
  69. #define WAIT_NOHANG(status)     waitpid (-1, (status), WNOHANG)
  70. #else    /* Don't have waitpid.  */
  71. #ifdef    HAVE_WAIT3
  72. #ifndef wait3
  73. extern int wait3 ();
  74. #endif
  75. #define WAIT_NOHANG(status)     wait3 ((status), WNOHANG, (struct rusage *) 0)
  76. #endif    /* Have wait3.    */
  77. #endif    /* Have waitpid.  */
  78.  
  79. #if    !defined (wait) && !defined (POSIX)
  80. extern int wait ();
  81. #endif
  82.  
  83. #ifndef HAVE_UNION_WAIT
  84.  
  85. #define WAIT_T int
  86.  
  87. #ifndef WTERMSIG
  88. #define WTERMSIG(x) ((x) & 0x7f)
  89. #endif
  90. #ifndef WCOREDUMP
  91. #define WCOREDUMP(x) ((x) & 0x80)
  92. #endif
  93. #ifndef WEXITSTATUS
  94. #define WEXITSTATUS(x) (((x) >> 8) & 0xff)
  95. #endif
  96. #ifndef WIFSIGNALED
  97. #define WIFSIGNALED(x) (WTERMSIG (x) != 0)
  98. #endif
  99. #ifndef WIFEXITED
  100. #define WIFEXITED(x) (WTERMSIG (x) == 0)
  101. #endif
  102.  
  103. #else    /* Have `union wait'.  */
  104.  
  105. #define WAIT_T union wait
  106. #ifndef WTERMSIG
  107. #define WTERMSIG(x)     ((x).w_termsig)
  108. #endif
  109. #ifndef WCOREDUMP
  110. #define WCOREDUMP(x)    ((x).w_coredump)
  111. #endif
  112. #ifndef WEXITSTATUS
  113. #define WEXITSTATUS(x)  ((x).w_retcode)
  114. #endif
  115. #ifndef WIFSIGNALED
  116. #define WIFSIGNALED(x)  (WTERMSIG(x) != 0)
  117. #endif
  118. #ifndef WIFEXITED
  119. #define WIFEXITED(x)    (WTERMSIG(x) == 0)
  120. #endif
  121.  
  122. #endif    /* Don't have `union wait'.  */
  123.  
  124.  
  125. #ifndef HAVE_UNISTD_H
  126. extern int dup2 ();
  127. extern int execve ();
  128. extern void _exit ();
  129. extern int geteuid (), getegid ();
  130. extern int setgid (), getgid ();
  131. #endif
  132.  
  133. #ifndef getdtablesize
  134. #ifdef HAVE_GETDTABLESIZE
  135. extern int getdtablesize ();
  136. #else
  137. #ifdef HAVE_SYSCONF_OPEN_MAX
  138. #define getdtablesize()         ((int) sysconf (_SC_OPEN_MAX))
  139. #else
  140. #ifdef HAVE_SYS_PARAM_H
  141. #include <sys/param.h>
  142. #endif
  143. #define getdtablesize() NOFILE
  144. #if !defined (NOFILE) && defined (NOFILES_MAX)
  145. /* SCO 3.2 "devsys 4.2" defines NOFILES_{MIN,MAX} in lieu of NOFILE.  */
  146. #define NOFILE    NOFILES_MAX
  147. #endif
  148. #if !defined (NOFILE) && defined (__SASC)
  149. #define NOFILE FOPEN_MAX
  150. #endif
  151. #endif
  152. #endif
  153.  
  154. extern int getloadavg ();
  155. extern int start_remote_job_p ();
  156. extern int start_remote_job (), remote_status ();
  157.  
  158. RETSIGTYPE child_handler ();
  159. static void free_child (), start_job_command ();
  160. static int load_too_high (), job_next_command ();
  161.  
  162. /* Chain of all live (or recently deceased) children.  */
  163.  
  164. struct child *children = 0;
  165.  
  166. /* Number of children currently running.  */
  167.  
  168. unsigned int job_slots_used = 0;
  169.  
  170. /* Nonzero if the `good' standard input is in use.  */
  171.  
  172. static int good_stdin_used = 0;
  173.  
  174. /* Chain of children waiting to run until the load average goes down.  */
  175.  
  176. static struct child *waiting_jobs = 0;
  177.  
  178. /* Write an error message describing the exit status given in
  179.    EXIT_CODE, EXIT_SIG, and COREDUMP, for the target TARGET_NAME.
  180.    Append "(ignored)" if IGNORED is nonzero.  */
  181.  
  182. static void
  183. child_error (target_name, exit_code, exit_sig, coredump, ignored)
  184.      char *target_name;
  185.      int exit_code, exit_sig, coredump;
  186.      int ignored;
  187. {
  188.   if (exit_sig == 0)
  189.     error (ignored ? "[%s] Error %d (ignored)" :
  190.        "*** [%s] Error %d",
  191.        target_name, exit_code);
  192.   else
  193.     error ("*** [%s] %s%s",
  194.        target_name, strsignal (exit_sig),
  195.        coredump ? " (core dumped)" : "");
  196. }
  197.  
  198. static unsigned int dead_children = 0;
  199.  
  200. /* Notice that a child died.
  201.    reap_children should be called when convenient.  */
  202. RETSIGTYPE
  203. child_handler (sig)
  204.      int sig;
  205. {
  206.   ++dead_children;
  207.  
  208.   if (debug_flag)
  209.     printf ("Got a SIGCHLD; %d unreaped children.\n", dead_children);
  210. }
  211.  
  212. extern int shell_function_pid, shell_function_completed;
  213.  
  214. /* Reap dead children, storing the returned status and the new command
  215.    state (`cs_finished') in the `file' member of the `struct child' for the
  216.    dead child, and removing the child from the chain.  If BLOCK nonzero,
  217.    reap at least one child, waiting for it to die if necessary.  If ERR is
  218.    nonzero, print an error message first.  */
  219.  
  220. void
  221. reap_children (block, err)
  222.      int block, err;
  223. {
  224.   WAIT_T status;
  225.  
  226.   while ((children != 0 || shell_function_pid != 0) &&
  227.      (block || dead_children > 0))
  228.     {
  229.       int remote = 0;
  230.       register int pid;
  231.       int exit_code, exit_sig, coredump;
  232.       register struct child *lastc, *c;
  233.       int child_failed;
  234.       int any_remote, any_local;
  235.  
  236.       if (err && dead_children == 0)
  237.     {
  238.       /* We might block for a while, so let the user know why.  */
  239.       fflush (stdout);
  240.       error ("*** Waiting for unfinished jobs....");
  241.     }
  242.  
  243.       /* We have one less dead child to reap.
  244.      The test and decrement are not atomic; if it is compiled into:
  245.         register = dead_children - 1;
  246.         dead_children = register;
  247.      a SIGCHLD could come between the two instructions.
  248.      child_handler increments dead_children.
  249.      The second instruction here would lose that increment.  But the
  250.      only effect of dead_children being wrong is that we might wait
  251.      longer than necessary to reap a child, and lose some parallelism;
  252.      and we might print the "Waiting for unfinished jobs" message above
  253.      when not necessary.  */
  254.  
  255.       if (dead_children != 0)
  256.     --dead_children;
  257.  
  258.       any_remote = 0;
  259.       any_local = shell_function_pid != -1;
  260.       for (c = children; c != 0; c = c->next)
  261.     {
  262.       any_remote |= c->remote;
  263.       any_local |= ! c->remote;
  264.       if (debug_flag)
  265.         printf ("Live child 0x%08lx PID %d%s\n",
  266.             (unsigned long int) c,
  267.             c->pid, c->remote ? " (remote)" : "");
  268.     }
  269.  
  270.       /* First, check for remote children.  */
  271.       if (any_remote)
  272.     pid = remote_status (&exit_code, &exit_sig, &coredump, 0);
  273.       else
  274.     pid = 0;
  275.       if (pid < 0)
  276.     {
  277.     remote_status_lose:
  278. #ifdef    EINTR
  279.       if (errno == EINTR)
  280.         continue;
  281. #endif
  282.       pfatal_with_name ("remote_status");
  283.     }
  284.       else if (pid == 0)
  285.     {
  286. #if !defined(__MSDOS__) && !defined(_AMIGA)
  287.       /* No remote children.  Check for local children.  */
  288.  
  289.       if (any_local)
  290.         {
  291. #ifdef    WAIT_NOHANG
  292.           if (!block)
  293.         pid = WAIT_NOHANG (&status);
  294.           else
  295. #endif
  296.         pid = wait (&status);
  297.         }
  298.       else
  299.         pid = 0;
  300.  
  301.       if (pid < 0)
  302.         {
  303. #ifdef    EINTR
  304.           if (errno == EINTR)
  305.         continue;
  306. #endif
  307.           pfatal_with_name ("wait");
  308.         }
  309.       else if (pid == 0)
  310.         {
  311.           /* No local children.  */
  312.           if (block && any_remote)
  313.         {
  314.           /* Now try a blocking wait for a remote child.  */
  315.           pid = remote_status (&exit_code, &exit_sig, &coredump, 1);
  316.           if (pid < 0)
  317.             goto remote_status_lose;
  318.           else if (pid == 0)
  319.             /* No remote children either.  Finally give up.  */
  320.             break;
  321.           else
  322.             /* We got a remote child.  */
  323.             remote = 1;
  324.         }
  325.           else
  326.         break;
  327.         }
  328.       else
  329.         {
  330.           /* Chop the status word up.  */
  331.           exit_code = WEXITSTATUS (status);
  332.           exit_sig = WIFSIGNALED (status) ? WTERMSIG (status) : 0;
  333.           coredump = WCOREDUMP (status);
  334.         }
  335. #else    /* MSDOS.  */
  336. #ifdef __MSDOS__
  337.       /* Life is very different on MSDOS.  */
  338.       pid = dos_pid - 1;
  339.       status = dos_status;
  340.       exit_code = dos_status;
  341.       exit_sig = 0;
  342.       coredump = 0;
  343. #else
  344.       /* Same on Amiga */
  345.       pid = amiga_pid - 1;
  346.       status = amiga_status;
  347.       exit_code = amiga_status;
  348.       exit_sig = 0;
  349.       coredump = 0;
  350. #endif
  351. #endif    /* Not MSDOS.  */
  352.     }
  353.       else
  354.     /* We got a remote child.  */
  355.     remote = 1;
  356.  
  357.       /* Check if this is the child of the `shell' function.  */
  358.       if (!remote && pid == shell_function_pid)
  359.     {
  360.       /* It is.  Leave an indicator for the `shell' function.  */
  361.       if (exit_sig == 0 && exit_code == 127)
  362.         shell_function_completed = -1;
  363.       else
  364.         shell_function_completed = 1;
  365.       break;
  366.     }
  367.  
  368.       child_failed = exit_sig != 0 || exit_code != 0;
  369.  
  370.       /* Search for a child matching the deceased one.    */
  371.       lastc = 0;
  372.       for (c = children; c != 0; lastc = c, c = c->next)
  373.     if (c->remote == remote && c->pid == pid)
  374.       break;
  375.  
  376.       if (c == 0)
  377.     {
  378.       /* An unknown child died.  */
  379.       char buf[100];
  380.       sprintf (buf, "Unknown%s job %d", remote ? " remote" : "", pid);
  381.       if (child_failed)
  382.         child_error (buf, exit_code, exit_sig, coredump,
  383.              ignore_errors_flag);
  384.       else
  385.         error ("%s finished.", buf);
  386.     }
  387.       else
  388.     {
  389.       if (debug_flag)
  390.         printf ("Reaping %s child 0x%08lx PID %d%s\n",
  391.             child_failed ? "losing" : "winning",
  392.             (unsigned long int) c,
  393.             c->pid, c->remote ? " (remote)" : "");
  394.  
  395.       /* If this child had the good stdin, say it is now free.  */
  396.       if (c->good_stdin)
  397.         good_stdin_used = 0;
  398.  
  399.       if (child_failed && !c->noerror && !ignore_errors_flag)
  400.         {
  401.           /* The commands failed.  Write an error message,
  402.          delete non-precious targets, and abort.  */
  403.           static int delete_on_error = -1;
  404.           child_error (c->file->name, exit_code, exit_sig, coredump, 0);
  405.           c->file->update_status = 2;
  406.           if (delete_on_error == -1)
  407.         {
  408.           struct file *f = lookup_file (".DELETE_ON_ERROR");
  409.           delete_on_error = f != 0 && f->is_target;
  410.         }
  411.           if (exit_sig != 0 || delete_on_error)
  412.         delete_child_targets (c);
  413.         }
  414.       else
  415.         {
  416.           if (child_failed)
  417.         {
  418.           /* The commands failed, but we don't care.  */
  419.           child_error (c->file->name,
  420.                    exit_code, exit_sig, coredump, 1);
  421.           child_failed = 0;
  422.         }
  423.  
  424.           /* If there are more commands to run, try to start them.    */
  425.           if (job_next_command (c))
  426.         {
  427.           if (handling_fatal_signal)
  428.             {
  429.               /* Never start new commands while we are dying.
  430.              Since there are more commands that wanted to be run,
  431.              the target was not completely remade.    So we treat
  432.              this as if a command had failed.  */
  433.               c->file->update_status = 2;
  434.             }
  435.           else
  436.             {
  437.               /* Check again whether to start remotely.
  438.              Whether or not we want to changes over time.
  439.              Also, start_remote_job may need state set up
  440.              by start_remote_job_p.  */
  441.               c->remote = start_remote_job_p ();
  442.               start_job_command (c);
  443.               if (c->file->command_state == cs_running)
  444.             /* We successfully started the new command.
  445.                Loop to reap more children.    */
  446.             continue;
  447.             }
  448.  
  449.           if (c->file->update_status != 0)
  450.             /* We failed to start the commands.  */
  451.             delete_child_targets (c);
  452.         }
  453.           else
  454.         /* There are no more commands.    We got through them all
  455.            without an unignored error.    Now the target has been
  456.            successfully updated.  */
  457.         c->file->update_status = 0;
  458.         }
  459.  
  460.       /* When we get here, all the commands for C->file are finished
  461.          (or aborted) and C->file->update_status contains 0 or 2.  But
  462.          C->file->command_state is still cs_running if all the commands
  463.          ran; notice_finish_file looks for cs_running to tell it that
  464.          it's interesting to check the file's modtime again now.  */
  465.  
  466.       if (! handling_fatal_signal)
  467.         /* Notice if the target of the commands has been changed.
  468.            This also propagates its values for command_state and
  469.            update_status to its also_make files.  */
  470.         notice_finished_file (c->file);
  471.  
  472.       if (debug_flag)
  473.         printf ("Removing child 0x%08lx PID %d%s from chain.\n",
  474.             (unsigned long int) c,
  475.             c->pid, c->remote ? " (remote)" : "");
  476.  
  477.       /* Remove the child from the chain and free it.  */
  478.       if (lastc == 0)
  479.         children = c->next;
  480.       else
  481.         lastc->next = c->next;
  482.       if (! handling_fatal_signal) /* Avoid nonreentrancy.  */
  483.         free_child (c);
  484.  
  485.       /* There is now another slot open.  */
  486.       --job_slots_used;
  487.  
  488.       /* If the job failed, and the -k flag was not given, die,
  489.          unless we are already in the process of dying.  */
  490.       if (!err && child_failed && !keep_going_flag)
  491.         die (2);
  492.     }
  493.  
  494.       /* Only block for one child.  */
  495.       block = 0;
  496.     }
  497. }
  498.  
  499. /* Free the storage allocated for CHILD.  */
  500.  
  501. static void
  502. free_child (child)
  503.      register struct child *child;
  504. {
  505.   if (child->command_lines != 0)
  506.     {
  507.       register unsigned int i;
  508.       for (i = 0; i < child->file->cmds->ncommand_lines; ++i)
  509.     free (child->command_lines[i]);
  510.       free ((char *) child->command_lines);
  511.     }
  512.  
  513.   if (child->environment != 0)
  514.     {
  515.       register char **ep = child->environment;
  516.       while (*ep != 0)
  517.     free (*ep++);
  518.       free ((char *) child->environment);
  519.     }
  520.  
  521.   free ((char *) child);
  522. }
  523.  
  524. #ifdef    POSIX
  525. #ifdef    __MSDOS__
  526. void
  527. unblock_sigs ()
  528. {
  529.   return;
  530. }
  531. #else
  532. extern sigset_t fatal_signal_set;
  533.  
  534. void
  535. unblock_sigs ()
  536. {
  537.   sigset_t empty;
  538.   sigemptyset (&empty);
  539.   sigprocmask (SIG_SETMASK, &empty, (sigset_t *) 0);
  540. }
  541. #endif
  542. #endif
  543.  
  544. /* Start a job to run the commands specified in CHILD.
  545.    CHILD is updated to reflect the commands and ID of the child process.  */
  546.  
  547. static void
  548. start_job_command (child)
  549.      register struct child *child;
  550. {
  551. #ifndef _AMIGA
  552.   static int bad_stdin = -1;
  553. #endif
  554.   register char *p;
  555.   int flags;
  556.   char **argv;
  557.  
  558.   /* Combine the flags parsed for the line itself with
  559.      the flags specified globally for this target.  */
  560.   flags = (child->file->command_flags
  561.        | child->file->cmds->lines_flags[child->command_line - 1]);
  562.  
  563.   p = child->command_ptr;
  564.   child->noerror = flags & COMMANDS_NOERROR;
  565.   while (*p != '\0')
  566.     {
  567.       if (*p == '@')
  568.     flags |= COMMANDS_SILENT;
  569.       else if (*p == '+')
  570.     flags |= COMMANDS_RECURSE;
  571.       else if (*p == '-')
  572.     child->noerror = 1;
  573.       else if (!isblank (*p) && *p != '+')
  574.     break;
  575.       ++p;
  576.     }
  577.  
  578.   /* If -q was given, just say that updating `failed'.  The exit status of
  579.      1 tells the user that -q is saying `something to do'; the exit status
  580.      for a random error is 2.  */
  581.   if (question_flag && !(flags & COMMANDS_RECURSE))
  582.     {
  583.       child->file->update_status = 1;
  584.       notice_finished_file (child->file);
  585.       return;
  586.     }
  587.  
  588.   /* There may be some preceding whitespace left if there
  589.      was nothing but a backslash on the first line.  */
  590.   p = next_token (p);
  591.  
  592.   /* Figure out an argument list from this command line.  */
  593.  
  594.   {
  595.     char *end;
  596.     argv = construct_command_argv (p, &end, child->file);
  597.     if (end == NULL)
  598.       child->command_ptr = NULL;
  599.     else
  600.       {
  601.     *end++ = '\0';
  602.     child->command_ptr = end;
  603.       }
  604.   }
  605.  
  606.   if (touch_flag && !(flags & COMMANDS_RECURSE))
  607.     {
  608.       /* Go on to the next command.  It might be the recursive one.
  609.      We construct ARGV only to find the end of the command line.  */
  610.       free (argv[0]);
  611.       free ((char *) argv);
  612.       argv = 0;
  613.     }
  614.  
  615.   if (argv == 0)
  616.     {
  617.     next_command:
  618.       /* This line has no commands.  Go to the next.  */
  619.       if (job_next_command (child))
  620.     start_job_command (child);
  621.       else
  622.     {
  623.       /* No more commands.    All done.  */
  624.       child->file->update_status = 0;
  625.       notice_finished_file (child->file);
  626.     }
  627.       return;
  628.     }
  629.  
  630.   /* Print out the command.  */
  631.  
  632.   if (just_print_flag || (!(flags & COMMANDS_SILENT) && !silent_flag))
  633.     puts (p);
  634.  
  635.   /* Tell update_goal_chain that a command has been started on behalf of
  636.      this target.  It is important that this happens here and not in
  637.      reap_children (where we used to do it), because reap_children might be
  638.      reaping children from a different target.    We want this increment to
  639.      guaranteedly indicate that a command was started for the dependency
  640.      chain (i.e., update_file recursion chain) we are processing.  */
  641.  
  642.   ++commands_started;
  643.  
  644.   /* If -n was given, recurse to get the next line in the sequence.  */
  645.  
  646.   if (just_print_flag && !(flags & COMMANDS_RECURSE))
  647.     {
  648.       free (argv[0]);
  649.       free ((char *) argv);
  650.       goto next_command;
  651.     }
  652.  
  653.   /* Flush the output streams so they won't have things written twice.  */
  654.  
  655.   fflush (stdout);
  656.   fflush (stderr);
  657.  
  658. #ifndef _AMIGA
  659.   /* Set up a bad standard input that reads from a broken pipe.  */
  660.   if (bad_stdin == -1)
  661.     {
  662.       /* Make a file descriptor that is the read end of a broken pipe.
  663.      This will be used for some children's standard inputs.  */
  664.       int pd[2];
  665.       if (pipe (pd) == 0)
  666.     {
  667.       /* Close the write side.  */
  668.       (void) close (pd[1]);
  669.       /* Save the read side.  */
  670.       bad_stdin = pd[0];
  671.     }
  672.     }
  673. #endif
  674.  
  675.   /* Decide whether to give this child the `good' standard input
  676.      (one that points to the terminal or whatever), or the `bad' one
  677.      that points to the read side of a broken pipe.  */
  678.  
  679.   child->good_stdin = !good_stdin_used;
  680.   if (child->good_stdin)
  681.     good_stdin_used = 1;
  682.  
  683.   child->deleted = 0;
  684.  
  685. #ifndef _AMIGA
  686.   /* Set up the environment for the child.  */
  687.   if (child->environment == 0)
  688.     child->environment = target_environment (child->file);
  689. #endif
  690.  
  691. #if !defined(__MSDOS__) && !defined(_AMIGA)
  692.  
  693.   /* start_waiting_job has set CHILD->remote if we can start a remote job.  */
  694.   if (child->remote)
  695.     {
  696.       int is_remote, id, used_stdin;
  697.       if (start_remote_job (argv, child->environment,
  698.                 child->good_stdin ? 0 : bad_stdin,
  699.                 &is_remote, &id, &used_stdin))
  700.     goto error;
  701.       else
  702.     {
  703.       if (child->good_stdin && !used_stdin)
  704.         {
  705.           child->good_stdin = 0;
  706.           good_stdin_used = 0;
  707.         }
  708.       child->remote = is_remote;
  709.       child->pid = id;
  710.     }
  711.     }
  712.   else
  713.     {
  714.       /* Fork the child process.  */
  715.  
  716.       char **parent_environ;
  717.  
  718. #ifdef     POSIX
  719.       (void) sigprocmask (SIG_BLOCK, &fatal_signal_set, (sigset_t *) 0);
  720. #else
  721. #ifdef    HAVE_SIGSETMASK
  722.       (void) sigblock (fatal_signal_mask);
  723. #endif
  724. #endif
  725.  
  726.       child->remote = 0;
  727.       parent_environ = environ;
  728.       child->pid = vfork ();
  729.       environ = parent_environ; /* Restore value child may have clobbered.  */
  730.       if (child->pid == 0)
  731.     {
  732.       /* We are the child side.  */
  733.       unblock_sigs ();
  734.       child_execute_job (child->good_stdin ? 0 : bad_stdin, 1,
  735.                  argv, child->environment);
  736.     }
  737.       else if (child->pid < 0)
  738.     {
  739.       /* Fork failed!  */
  740.       unblock_sigs ();
  741.       perror_with_name ("vfork", "");
  742.       goto error;
  743.     }
  744.     }
  745.  
  746. #else    /* MSDOS or Amiga  */
  747. #ifndef _AMIGA
  748.   dos_status = spawnvpe (P_WAIT, argv[0], argv, child->environment);
  749.   ++dead_children;
  750.   child->pid = dos_pid++;
  751.   if (dos_batch_file)
  752.    {
  753.      dos_batch_file = 0;
  754.      remove (dos_bname);        /* Ignore errors.  */
  755.      if (access (dos_bename, 0))
  756.        dos_status = 1;
  757.      else
  758.        dos_status = 0;
  759.      remove (dos_bename);
  760.    }
  761. #else
  762.   amiga_status = MyExecute (argv);
  763.  
  764.   ++dead_children;
  765.   child->pid = amiga_pid++;
  766.   if (amiga_batch_file)
  767.   {
  768.      amiga_batch_file = 0;
  769.      DeleteFile (amiga_bname);        /* Ignore errors.  */
  770.   }
  771. #endif    /* Not Amiga */
  772. #endif    /* Not MSDOS.  */
  773.  
  774.   /* We are the parent side.  Set the state to
  775.      say the commands are running and return.  */
  776.  
  777.   set_command_state (child->file, cs_running);
  778.  
  779.   /* Free the storage used by the child's argument list.  */
  780.  
  781.   free (argv[0]);
  782.   free ((char *) argv);
  783.  
  784.   return;
  785.  
  786.  error:
  787.   child->file->update_status = 2;
  788.   notice_finished_file (child->file);
  789. }
  790.  
  791. /* Try to start a child running.
  792.    Returns nonzero if the child was started (and maybe finished), or zero if
  793.    the load was too high and the child was put on the `waiting_jobs' chain.  */
  794.  
  795. static int
  796. start_waiting_job (c)
  797.      struct child *c;
  798. {
  799.   /* If we can start a job remotely, we always want to, and don't care about
  800.      the local load average.  We record that the job should be started
  801.      remotely in C->remote for start_job_command to test.  */
  802.  
  803.   c->remote = start_remote_job_p ();
  804.  
  805.   /* If this job is to be started locally, and we are already running
  806.      some jobs, make this one wait if the load average is too high.  */
  807.   if (!c->remote && job_slots_used > 0 && load_too_high ())
  808.     {
  809.       /* Put this child on the chain of children waiting
  810.      for the load average to go down.  */
  811.       set_command_state (c->file, cs_running);
  812.       c->next = waiting_jobs;
  813.       waiting_jobs = c;
  814.       return 0;
  815.     }
  816.  
  817.   /* Start the first command; reap_children will run later command lines.  */
  818.   start_job_command (c);
  819.  
  820.   switch (c->file->command_state)
  821.     {
  822.     case cs_running:
  823.       c->next = children;
  824.       if (debug_flag)
  825.     printf ("Putting child 0x%08lx PID %05d%s on the chain.\n",
  826.         (unsigned long int) c,
  827.         c->pid, c->remote ? " (remote)" : "");
  828.       children = c;
  829.       /* One more job slot is in use.  */
  830.       ++job_slots_used;
  831.       unblock_sigs ();
  832.       break;
  833.  
  834.     case cs_not_started:
  835.       /* All the command lines turned out to be empty.    */
  836.       c->file->update_status = 0;
  837.       /* FALLTHROUGH */
  838.  
  839.     case cs_finished:
  840.       notice_finished_file (c->file);
  841.       free_child (c);
  842.       break;
  843.  
  844.     default:
  845.       assert (c->file->command_state == cs_finished);
  846.       break;
  847.     }
  848.  
  849.   return 1;
  850. }
  851.  
  852. /* Create a `struct child' for FILE and start its commands running.  */
  853.  
  854. void
  855. new_job (file)
  856.      register struct file *file;
  857. {
  858.   register struct commands *cmds = file->cmds;
  859.   register struct child *c;
  860.   char **lines;
  861.   register unsigned int i;
  862.  
  863.   /* Let any previously decided-upon jobs that are waiting
  864.      for the load to go down start before this new one.  */
  865.   start_waiting_jobs ();
  866.  
  867.   /* Reap any children that might have finished recently.  */
  868.   reap_children (0, 0);
  869.  
  870.   /* Chop the commands up into lines if they aren't already.  */
  871.   chop_commands (cmds);
  872.  
  873.   if (job_slots != 0)
  874.     /* Wait for a job slot to be freed up.  */
  875.     while (job_slots_used == job_slots)
  876.       reap_children (1, 0);
  877.  
  878.   /* Expand the command lines and store the results in LINES.  */
  879.   lines = (char **) xmalloc (cmds->ncommand_lines * sizeof (char *));
  880.   for (i = 0; i < cmds->ncommand_lines; ++i)
  881.     {
  882.       /* Collapse backslash-newline combinations that are inside variable
  883.      or function references.  These are left alone by the parser so
  884.      that they will appear in the echoing of commands (where they look
  885.      nice); and collapsed by construct_command_argv when it tokenizes.
  886.      But letting them survive inside function invocations loses because
  887.      we don't want the functions to see them as part of the text.  */
  888.  
  889.       char *in, *out, *ref;
  890.  
  891.       /* IN points to where in the line we are scanning.
  892.      OUT points to where in the line we are writing.
  893.      When we collapse a backslash-newline combination,
  894.      IN gets ahead out OUT.  */
  895.  
  896.       in = out = cmds->command_lines[i];
  897.       while ((ref = index (in, '$')) != 0)
  898.     {
  899.       ++ref;        /* Move past the $.  */
  900.  
  901.       if (out != in)
  902.         /* Copy the text between the end of the last chunk
  903.            we processed (where IN points) and the new chunk
  904.            we are about to process (where REF points).  */
  905.         bcopy (in, out, ref - in);
  906.  
  907.       /* Move both pointers past the boring stuff.    */
  908.       out += ref - in;
  909.       in = ref;
  910.  
  911.       if (*ref == '(' || *ref == '{')
  912.         {
  913.           char openparen = *ref;
  914.           char closeparen = openparen == '(' ? ')' : '}';
  915.           int count;
  916.           char *p;
  917.  
  918.           *out++ = *in++;    /* Copy OPENPAREN.  */
  919.           /* IN now points past the opening paren or brace.
  920.          Count parens or braces until it is matched.  */
  921.           count = 0;
  922.           while (*in != '\0')
  923.         {
  924.           if (*in == closeparen && --count < 0)
  925.             break;
  926.           else if (*in == '\\' && in[1] == '\n')
  927.             {
  928.               /* We have found a backslash-newline inside a
  929.              variable or function reference.  Eat it and
  930.              any following whitespace.  */
  931.  
  932.               int quoted = 0;
  933.               for (p = in - 1; p > ref && *p == '\\'; --p)
  934.             quoted = !quoted;
  935.  
  936.               if (quoted)
  937.             /* There were two or more backslashes, so this is
  938.                not really a continuation line.  We don't collapse
  939.                the quoting backslashes here as is done in
  940.                collapse_continuations, because the line will
  941.                be collapsed again after expansion.    */
  942.             *out++ = *in++;
  943.               else
  944.             {
  945.               /* Skip the backslash, newline and
  946.                  any following whitespace.    */
  947.               in = next_token (in + 2);
  948.  
  949.               /* Discard any preceding whitespace that has
  950.                  already been written to the output.  */
  951.               while (out > ref && isblank (out[-1]))
  952.                 --out;
  953.  
  954.               /* Replace it all with a single space.  */
  955.               *out++ = ' ';
  956.             }
  957.             }
  958.           else
  959.             {
  960.               if (*in == openparen)
  961.             ++count;
  962.  
  963.               *out++ = *in++;
  964.             }
  965.         }
  966.         }
  967.     }
  968.  
  969.       /* There are no more references in this line to worry about.
  970.      Copy the remaining uninteresting text to the output.  */
  971.       if (out != in)
  972.     strcpy (out, in);
  973.  
  974.       /* Finally, expand the line.  */
  975.       lines[i] = allocated_variable_expand_for_file (cmds->command_lines[i],
  976.                              file);
  977.     }
  978.  
  979.   /* Start the command sequence, record it in a new
  980.      `struct child', and add that to the chain.  */
  981.  
  982.   c = (struct child *) xmalloc (sizeof (struct child));
  983.   c->file = file;
  984.   c->command_lines = lines;
  985.   c->command_line = 0;
  986.   c->command_ptr = 0;
  987.   c->environment = 0;
  988.  
  989.   /* Fetch the first command line to be run.  */
  990.   job_next_command (c);
  991.  
  992.   /* The job is now primed.  Start it running.
  993.      (This will notice if there are in fact no commands.)  */
  994.   start_waiting_job (c);
  995.  
  996.   if (job_slots == 1)
  997.     /* Since there is only one job slot, make things run linearly.
  998.        Wait for the child to die, setting the state to `cs_finished'.  */
  999.     while (file->command_state == cs_running)
  1000.       reap_children (1, 0);
  1001. }
  1002.  
  1003. /* Move CHILD's pointers to the next command for it to execute.
  1004.    Returns nonzero if there is another command.  */
  1005.  
  1006. static int
  1007. job_next_command (child)
  1008.      struct child *child;
  1009. {
  1010.   while (child->command_ptr == 0 || *child->command_ptr == '\0')
  1011.     {
  1012.       /* There are no more lines in the expansion of this line.  */
  1013.       if (child->command_line == child->file->cmds->ncommand_lines)
  1014.     {
  1015.       /* There are no more lines to be expanded.  */
  1016.       child->command_ptr = 0;
  1017.       return 0;
  1018.     }
  1019.       else
  1020.     /* Get the next line to run.  */
  1021.     child->command_ptr = child->command_lines[child->command_line++];
  1022.     }
  1023.   return 1;
  1024. }
  1025.  
  1026. static int
  1027. load_too_high ()
  1028. {
  1029. #if defined(__MSDOS__) || defined(_AMIGA)
  1030.   return 1;
  1031. #else
  1032.   extern int getloadavg ();
  1033.   double load;
  1034.  
  1035.   if (max_load_average < 0)
  1036.     return 0;
  1037.  
  1038.   make_access ();
  1039.   if (getloadavg (&load, 1) != 1)
  1040.     {
  1041.       static int lossage = -1;
  1042.       /* Complain only once for the same error.  */
  1043.       if (lossage == -1 || errno != lossage)
  1044.     {
  1045.       if (errno == 0)
  1046.         /* An errno value of zero means getloadavg is just unsupported.  */
  1047.         error ("cannot enforce load limits on this operating system");
  1048.       else
  1049.         perror_with_name ("cannot enforce load limit: ", "getloadavg");
  1050.     }
  1051.       lossage = errno;
  1052.       load = 0;
  1053.     }
  1054.   user_access ();
  1055.  
  1056.   return load >= max_load_average;
  1057. #endif
  1058. }
  1059.  
  1060. /* Start jobs that are waiting for the load to be lower.  */
  1061.  
  1062. void
  1063. start_waiting_jobs ()
  1064. {
  1065.   struct child *job;
  1066.  
  1067.   if (waiting_jobs == 0)
  1068.     return;
  1069.  
  1070.   do
  1071.     {
  1072.       /* Check for recently deceased descendants.  */
  1073.       reap_children (0, 0);
  1074.  
  1075.       /* Take a job off the waiting list.  */
  1076.       job = waiting_jobs;
  1077.       waiting_jobs = job->next;
  1078.  
  1079.       /* Try to start that job.  We break out of the loop as soon
  1080.      as start_waiting_job puts one back on the waiting list.  */
  1081.     } while (start_waiting_job (job) && waiting_jobs != 0);
  1082. }
  1083.  
  1084. #ifndef _AMIGA
  1085. /* Replace the current process with one executing the command in ARGV.
  1086.    STDIN_FD and STDOUT_FD are used as the process's stdin and stdout; ENVP is
  1087.    the environment of the new program.    This function does not return.    */
  1088.  
  1089. void
  1090. child_execute_job (stdin_fd, stdout_fd, argv, envp)
  1091.      int stdin_fd, stdout_fd;
  1092.      char **argv, **envp;
  1093. {
  1094.   if (stdin_fd != 0)
  1095.     (void) dup2 (stdin_fd, 0);
  1096.   if (stdout_fd != 1)
  1097.     (void) dup2 (stdout_fd, 1);
  1098.  
  1099.   /* Free up file descriptors.    */
  1100.   {
  1101.     register int d;
  1102.     int max = getdtablesize ();
  1103.     for (d = 3; d < max; ++d)
  1104.       (void) close (d);
  1105.   }
  1106.  
  1107.   /* Run the command.  */
  1108.   exec_command (argv, envp);
  1109. }
  1110.  
  1111. /* Replace the current process with one running the command in ARGV,
  1112.    with environment ENVP.  This function does not return. */
  1113.  
  1114. void
  1115. exec_command (argv, envp)
  1116.      char **argv, **envp;
  1117. {
  1118.   /* Be the user, permanently.    */
  1119.   child_access ();
  1120.  
  1121.   /* Run the program.  */
  1122.   environ = envp;
  1123.   execvp (argv[0], argv);
  1124.  
  1125.   switch (errno)
  1126.     {
  1127.     case ENOENT:
  1128.       error ("%s: Command not found", argv[0]);
  1129.       break;
  1130.     case ENOEXEC:
  1131.       {
  1132.     /* The file is not executable.    Try it as a shell script.  */
  1133.     extern char *getenv ();
  1134.     char *shell;
  1135.     char **new_argv;
  1136.     int argc;
  1137.  
  1138.     shell = getenv ("SHELL");
  1139.     if (shell == 0)
  1140.       shell = default_shell;
  1141.  
  1142.     argc = 1;
  1143.     while (argv[argc] != 0)
  1144.       ++argc;
  1145.  
  1146.     new_argv = (char **) alloca ((1 + argc + 1) * sizeof (char *));
  1147.     new_argv[0] = shell;
  1148.     new_argv[1] = program;
  1149.     while (argc > 0)
  1150.       {
  1151.         new_argv[1 + argc] = argv[argc];
  1152.         --argc;
  1153.       }
  1154.  
  1155.     execvp (shell, new_argv);
  1156.     if (errno == ENOENT)
  1157.       error ("%s: Shell program not found", shell);
  1158.     else
  1159.       perror_with_name ("execvp: ", shell);
  1160.     break;
  1161.       }
  1162.  
  1163.     default:
  1164.       perror_with_name ("execvp: ", argv[0]);
  1165.       break;
  1166.     }
  1167.  
  1168.   _exit (127);
  1169. }
  1170. #else /* On Amiga */
  1171. void exec_command (argv, envp)
  1172.      char **argv, **envp;
  1173. {
  1174.     MyExecute (argv);
  1175. }
  1176.  
  1177. void clean_tmp (void)
  1178. {
  1179.     DeleteFile (amiga_bname);
  1180. }
  1181.  
  1182. #endif /* An Amiga */
  1183.  
  1184. /* Figure out the argument list necessary to run LINE as a command.  Try to
  1185.    avoid using a shell.  This routine handles only ' quoting, and " quoting
  1186.    when no backslash, $ or ` characters are seen in the quotes.  Starting
  1187.    quotes may be escaped with a backslash.  If any of the characters in
  1188.    sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
  1189.    is the first word of a line, the shell is used.
  1190.  
  1191.    If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
  1192.    If *RESTP is NULL, newlines will be ignored.
  1193.  
  1194.    SHELL is the shell to use, or nil to use the default shell.
  1195.    IFS is the value of $IFS, or nil (meaning the default).  */
  1196.  
  1197. static char **
  1198. construct_command_argv_internal (line, restp, shell, ifs)
  1199.      char *line, **restp;
  1200.      char *shell, *ifs;
  1201. {
  1202. #ifdef __MSDOS__
  1203.   static char sh_chars[] = "\"|<>";
  1204.   static char *sh_cmds[] = { "break", "call", "cd", "chcp", "chdir", "cls",
  1205.                  "copy", "ctty", "date", "del", "dir", "echo",
  1206.                  "erase", "exit", "for", "goto", "if", "if", "md",
  1207.                  "mkdir", "path", "pause", "prompt", "rem", "ren",
  1208.                  "rename", "set", "shift", "time", "type",
  1209.                  "ver", "verify", "vol", ":", 0 };
  1210. #endif
  1211. #ifdef _AMIGA
  1212.   static char sh_chars[] = "#;\"|<>()?*$`";
  1213.   static char *sh_cmds[] = { "cd", "eval", "if", "delete", "echo", "copy",
  1214.                  "rename", "set", "setenv", "date", "makedir",
  1215.                  "skip", "else", "endif", "path", "prompt",
  1216.                  "unset", "unsetenv", "version",
  1217.                  0 };
  1218. #else
  1219.   static char sh_chars[] = "#;\"*?[]&|<>(){}$`^";
  1220.   static char *sh_cmds[] = { "cd", "eval", "exec", "exit", "login",
  1221.                  "logout", "set", "umask", "wait", "while", "for",
  1222.                  "case", "if", ":", ".", "break", "continue",
  1223.                  "export", "read", "readonly", "shift", "times",
  1224.                  "trap", "switch", 0 };
  1225. #endif
  1226.   register int i;
  1227.   register char *p;
  1228.   register char *ap;
  1229.   char *end;
  1230.   int instring, word_has_equals, seen_nonequals;
  1231.   char **new_argv = 0;
  1232.  
  1233.   if (restp != NULL)
  1234.     *restp = NULL;
  1235.  
  1236.   /* Make sure not to bother processing an empty line.    */
  1237.   while (isblank (*line))
  1238.     ++line;
  1239.   if (*line == '\0')
  1240.     return 0;
  1241.  
  1242.   /* See if it is safe to parse commands internally.  */
  1243.   if (shell == 0)
  1244.     shell = default_shell;
  1245.   else if (strcmp (shell, default_shell))
  1246.     goto slow;
  1247.  
  1248.   if (ifs != 0)
  1249.     for (ap = ifs; *ap != '\0'; ++ap)
  1250.       if (*ap != ' ' && *ap != '\t' && *ap != '\n')
  1251.     goto slow;
  1252.  
  1253.   i = strlen (line) + 1;
  1254.  
  1255.   /* More than 1 arg per character is impossible.  */
  1256.   new_argv = (char **) xmalloc (i * sizeof (char *));
  1257.  
  1258.   /* All the args can fit in a buffer as big as LINE is.   */
  1259.   ap = new_argv[0] = (char *) xmalloc (i);
  1260.   end = ap + i;
  1261.  
  1262.   /* I is how many complete arguments have been found.    */
  1263.   i = 0;
  1264.   instring = word_has_equals = seen_nonequals = 0;
  1265.   for (p = line; *p != '\0'; ++p)
  1266.     {
  1267.       if (ap > end)
  1268.     abort ();
  1269.  
  1270.       if (instring)
  1271.     {
  1272.     string_char:
  1273.       /* Inside a string, just copy any char except a closing quote
  1274.          or a backslash-newline combination.  */
  1275.       if (*p == instring)
  1276.         instring = 0;
  1277.       else if (*p == '\\' && p[1] == '\n')
  1278.         goto swallow_escaped_newline;
  1279.       else if (*p == '\n' && restp != NULL)
  1280.         {
  1281.           /* End of the command line.  */
  1282.           *restp = p;
  1283.           goto end_of_line;
  1284.         }
  1285.       /* Backslash, $, and ` are special inside double quotes.
  1286.          If we see any of those, punt.  */
  1287.       else if (instring == '"' && index ("\\$`", *p) != 0)
  1288.         goto slow;
  1289.       else
  1290.         *ap++ = *p;
  1291.     }
  1292.       else if (index (sh_chars, *p) != 0)
  1293.     /* Not inside a string, but it's a special char.  */
  1294.     goto slow;
  1295.       else
  1296.     /* Not a special char.    */
  1297.     switch (*p)
  1298.       {
  1299.       case '=':
  1300.         /* Equals is a special character in leading words before the
  1301.            first word with no equals sign in it.  This is not the case
  1302.            with sh -k, but we never get here when using nonstandard
  1303.            shell flags.  */
  1304.         if (! seen_nonequals)
  1305.           goto slow;
  1306.         word_has_equals = 1;
  1307.         *ap++ = '=';
  1308.         break;
  1309.  
  1310.       case '\\':
  1311.         /* Backslash-newline combinations are eaten.  */
  1312.         if (p[1] == '\n')
  1313.           {
  1314.           swallow_escaped_newline:
  1315.  
  1316.         /* Eat the backslash, the newline, and following whitespace,
  1317.            replacing it all with a single space.  */
  1318.         p += 2;
  1319.  
  1320.         /* If there is a tab after a backslash-newline,
  1321.            remove it from the source line which will be echoed,
  1322.            since it was most likely used to line
  1323.            up the continued line with the previous one.  */
  1324.         if (*p == '\t')
  1325.           strcpy (p, p + 1);
  1326.  
  1327.         if (instring)
  1328.           goto string_char;
  1329.         else
  1330.           {
  1331.             if (ap != new_argv[i])
  1332.               /* Treat this as a space, ending the arg.
  1333.              But if it's at the beginning of the arg, it should
  1334.              just get eaten, rather than becoming an empty arg. */
  1335.               goto end_of_arg;
  1336.             else
  1337.               p = next_token (p) - 1;
  1338.           }
  1339.           }
  1340.         else if (p[1] != '\0')
  1341.           /* Copy and skip the following char.  */
  1342.           *ap++ = *++p;
  1343.         break;
  1344.  
  1345.       case '\'':
  1346.       case '"':
  1347.         instring = *p;
  1348.         break;
  1349.  
  1350.       case '\n':
  1351.         if (restp != NULL)
  1352.           {
  1353.         /* End of the command line.  */
  1354.         *restp = p;
  1355.         goto end_of_line;
  1356.           }
  1357.         else
  1358.           /* Newlines are not special.  */
  1359.           *ap++ = '\n';
  1360.         break;
  1361.  
  1362.       case ' ':
  1363.       case '\t':
  1364.       end_of_arg:
  1365.         /* We have the end of an argument.
  1366.            Terminate the text of the argument.  */
  1367.         *ap++ = '\0';
  1368.         new_argv[++i] = ap;
  1369.  
  1370.         /* Update SEEN_NONEQUALS, which tells us if every word
  1371.            heretofore has contained an `='.  */
  1372.         seen_nonequals |= ! word_has_equals;
  1373.         if (word_has_equals && ! seen_nonequals)
  1374.           /* An `=' in a word before the first
  1375.          word without one is magical.  */
  1376.           goto slow;
  1377.         word_has_equals = 0; /* Prepare for the next word.    */
  1378.  
  1379.         /* If this argument is the command name,
  1380.            see if it is a built-in shell command.
  1381.            If so, have the shell handle it.  */
  1382.         if (i == 1)
  1383.           {
  1384.         register int j;
  1385.         for (j = 0; sh_cmds[j] != 0; ++j)
  1386.           if (streq (sh_cmds[j], new_argv[0]))
  1387.             goto slow;
  1388.           }
  1389.  
  1390.         /* Ignore multiple whitespace chars.  */
  1391.         p = next_token (p);
  1392.         /* Next iteration should examine the first nonwhite char.  */
  1393.         --p;
  1394.         break;
  1395.  
  1396.       default:
  1397.         *ap++ = *p;
  1398.         break;
  1399.       }
  1400.     }
  1401.  end_of_line:
  1402.  
  1403.   if (instring)
  1404.     /* Let the shell deal with an unterminated quote.  */
  1405.     goto slow;
  1406.  
  1407.   /* Terminate the last argument and the argument list.  */
  1408.  
  1409.   *ap = '\0';
  1410.   if (new_argv[i][0] != '\0')
  1411.     ++i;
  1412.   new_argv[i] = 0;
  1413.  
  1414.   if (i == 1)
  1415.     {
  1416.       register int j;
  1417.       for (j = 0; sh_cmds[j] != 0; ++j)
  1418.     if (streq (sh_cmds[j], new_argv[0]))
  1419.       goto slow;
  1420.     }
  1421.  
  1422.   if (new_argv[0] == 0)
  1423.     /* Line was empty.    */
  1424.     return 0;
  1425.   else
  1426.     return new_argv;
  1427.  
  1428.  slow:;
  1429.   /* We must use the shell.  */
  1430.  
  1431.   if (new_argv != 0)
  1432.     {
  1433.       /* Free the old argument list we were working on.  */
  1434.       free (new_argv[0]);
  1435.       free (new_argv);
  1436.     }
  1437.  
  1438. #ifdef __MSDOS__
  1439.    {
  1440.      FILE *batch;
  1441.      dos_batch_file = 1;
  1442.      if (dos_bname == 0)
  1443.        {
  1444.      dos_bname = tempnam (".", "mk");
  1445.      for (i = 0; dos_bname[i] != '\0'; ++i)
  1446.        if (dos_bname[i] == '/')
  1447.          dos_bname[i] = '\\';
  1448.      dos_bename = (char *) xmalloc (strlen (dos_bname) + 5);
  1449.      strcpy (dos_bename, dos_bname);
  1450.      strcat (dos_bname, ".bat");
  1451.      strcat (dos_bename, ".err");
  1452.        }
  1453.      batch = fopen (dos_bename, "w"); /* Create a file.  */
  1454.      if (batch != NULL)
  1455.        fclose (batch);
  1456.      batch = fopen (dos_bname, "w");
  1457.      fputs ("@echo off\n", batch);
  1458.      fputs (line, batch);
  1459.      fprintf (batch, "\nif errorlevel 1 del %s\n", dos_bename);
  1460.      fclose (batch);
  1461.      new_argv = (char **) xmalloc(2 * sizeof(char *));
  1462.      new_argv[0] = strdup (dos_bname);
  1463.      new_argv[1] = 0;
  1464.    }
  1465. #endif /* MSDOS. */
  1466. #ifdef _AMIGA
  1467.    {
  1468.      char *ptr;
  1469.      char *buffer;
  1470.      char *dptr;
  1471.  
  1472.      buffer = (char *)xmalloc (strlen (line)+1);
  1473.  
  1474.      ptr = line;
  1475.      for (dptr=buffer; *ptr; )
  1476.      {
  1477.     if (*ptr == '\\' && ptr[1] == '\n')
  1478.         ptr += 2;
  1479.     else if (*ptr == '@') /* Kludge: multiline commands */
  1480.     {
  1481.         ptr += 2;
  1482.         *dptr++ = '\n';
  1483.     }
  1484.     else
  1485.         *dptr++ = *ptr++;
  1486.      }
  1487.      *dptr = 0;
  1488.  
  1489.      new_argv = (char **) xmalloc(2 * sizeof(char *));
  1490.      new_argv[0] = buffer;
  1491.      new_argv[1] = 0;
  1492.    }
  1493. #else    /* Not MSDOS or Amiga  */
  1494.   {
  1495.     /* SHELL may be a multi-word command.  Construct a command line
  1496.        "SHELL -c LINE", with all special chars in LINE escaped.
  1497.        Then recurse, expanding this command line to get the final
  1498.        argument list.  */
  1499.  
  1500.     unsigned int shell_len = strlen (shell);
  1501.     static char minus_c[] = " -c ";
  1502.     unsigned int line_len = strlen (line);
  1503.  
  1504.     char *new_line = (char *) alloca (shell_len + (sizeof (minus_c) - 1)
  1505.                       + (line_len * 2) + 1);
  1506.  
  1507.     ap = new_line;
  1508.     bcopy (shell, ap, shell_len);
  1509.     ap += shell_len;
  1510.     bcopy (minus_c, ap, sizeof (minus_c) - 1);
  1511.     ap += sizeof (minus_c) - 1;
  1512.     for (p = line; *p != '\0'; ++p)
  1513.       {
  1514.     if (restp != NULL && *p == '\n')
  1515.       {
  1516.         *restp = p;
  1517.         break;
  1518.       }
  1519.     else if (*p == '\\' && p[1] == '\n')
  1520.       {
  1521.         /* Eat the backslash, the newline, and following whitespace,
  1522.            replacing it all with a single space (which is escaped
  1523.            from the shell).  */
  1524.         p += 2;
  1525.  
  1526.         /* If there is a tab after a backslash-newline,
  1527.            remove it from the source line which will be echoed,
  1528.            since it was most likely used to line
  1529.            up the continued line with the previous one.  */
  1530.         if (*p == '\t')
  1531.           strcpy (p, p + 1);
  1532.  
  1533.         p = next_token (p);
  1534.         --p;
  1535.         *ap++ = '\\';
  1536.         *ap++ = ' ';
  1537.         continue;
  1538.       }
  1539.  
  1540.     if (*p == '\\' || *p == '\'' || *p == '"'
  1541.         || isspace (*p)
  1542.         || index (sh_chars, *p) != 0)
  1543.       *ap++ = '\\';
  1544.     *ap++ = *p;
  1545.       }
  1546.     *ap = '\0';
  1547.  
  1548.     new_argv = construct_command_argv_internal (new_line, (char **) NULL,
  1549.                         (char *) 0, (char *) 0);
  1550.   }
  1551. #endif    /* Not MSDOS nor Amiga.  */
  1552.  
  1553.   return new_argv;
  1554. }
  1555.  
  1556. /* Figure out the argument list necessary to run LINE as a command.  Try to
  1557.    avoid using a shell.  This routine handles only ' quoting, and " quoting
  1558.    when no backslash, $ or ` characters are seen in the quotes.  Starting
  1559.    quotes may be escaped with a backslash.  If any of the characters in
  1560.    sh_chars[] is seen, or any of the builtin commands listed in sh_cmds[]
  1561.    is the first word of a line, the shell is used.
  1562.  
  1563.    If RESTP is not NULL, *RESTP is set to point to the first newline in LINE.
  1564.    If *RESTP is NULL, newlines will be ignored.
  1565.  
  1566.    FILE is the target whose commands these are.  It is used for
  1567.    variable expansion for $(SHELL) and $(IFS).  */
  1568.  
  1569. char **
  1570. construct_command_argv (line, restp, file)
  1571.      char *line, **restp;
  1572.      struct file *file;
  1573. {
  1574.   char *shell, *ifs;
  1575.   char **argv;
  1576.  
  1577.   {
  1578.     /* Turn off --warn-undefined-variables while we expand SHELL and IFS.  */
  1579.     int save = warn_undefined_variables_flag;
  1580.     warn_undefined_variables_flag = 0;
  1581.  
  1582.     shell = allocated_variable_expand_for_file ("$(SHELL)", file);
  1583.     ifs = allocated_variable_expand_for_file ("$(IFS)", file);
  1584.  
  1585.     warn_undefined_variables_flag = save;
  1586.   }
  1587.  
  1588.   argv = construct_command_argv_internal (line, restp, shell, ifs);
  1589.  
  1590.   free (shell);
  1591.   free (ifs);
  1592.  
  1593.   return argv;
  1594. }
  1595.  
  1596. #if !defined(HAVE_DUP2) && !defined(_AMIGA)
  1597. int
  1598. dup2 (old, new)
  1599.      int old, new;
  1600. {
  1601.   int fd;
  1602.  
  1603.   (void) close (new);
  1604.   fd = dup (old);
  1605.   if (fd != new)
  1606.     {
  1607.       (void) close (fd);
  1608.       errno = EMFILE;
  1609.       return -1;
  1610.     }
  1611.  
  1612.   return fd;
  1613. }
  1614. #endif /* !HAPE_DUP2 && !_AMIGA */
  1615.